"use strict";
var $structure_usercheck, $selectUserCheck, $fn_UserPass;
var $structure_usermng;
var $structure_authoruty, $fn_authoruty, $data_authoruty, _nodeAuthority;
var $structure_data, $fn_saveAuthData, $userData_table, $userData_tree, _userData_id;
var _fid, _uName, _uEmail;

function init() {
	var uid = vw_static.getCookie(window.location.host);
	_fid = vw_static.getQueryString(window, "fid");
	_uName = vw_static.getCookie(uid).split('|')[0];
	_uEmail = vw_static.getCookie(uid).split('|')[4];

	$structure_usercheck = $('#structure_usercheck');
	$structure_usermng = $('#structure_usermng');
	$structure_authoruty = $('#structure_authoruty');
	$structure_data = $('#structure_data');

	var subFunction = [
		'<ul class="nav nav-pills navbar-left" style="margin: 10px 0 0 100px;">',
		'	{{#items}}<li class="{{class}}" style="margin-left: 10px;">',
		'		<a href="#{{tab}}" class="btn btn-custom" data-toggle="tab"><i class="fa fa-{{icon}}"></i> {{name}}</a>',
		'	</li>{{/items}}',
		'</ul>'
	].join('');

	require(['mustache'], function(mustache) {
		$('#vw-navbar-custom').append(mustache.render(subFunction, {
			"items": [{
				"tab": "tab_usercheck",
				"class": "active",
				"icon": "user-circle-o",
				"name": "用户审核"
			}, {
				"tab": "tab_usermng",
				"icon": "user",
				"name": "用户管理"
			}, {
				"tab": "tab_authoruty",
				"icon": "sitemap",
				"name": "功能权限"
			}, {
				"tab": "tab_data",
				"icon": "database",
				"name": "数据权限"
			}]
		})).on('click', 'a', function() {
			switch($(this).attr("href")) {
				case "#tab_usercheck":
					$selectUserCheck.val(0).trigger("change");
					InitTab_UserCheck(0);
					break;
				case "#tab_usermng":
					InitTab_Usermng();
					break;
				case "#tab_authoruty":
					InitTab_UserAuthority();
					break;
				case "#tab_data":
					InitTab_UserData();
					break;
			}
		});
	});

	InitTab_UserCheck(0);
}

function InitTab_UserCheck(checkstat) {
	var html = [
		'<div class="pull-left" style="margin-right: 20px;background-color: #f7f7f9;border: 1px solid #e1e1e8; border-radius: 4px;padding: 3px 10px;">',
		'	<strong>审核状态：</strong>',
		'	<select id="select_userCheck" style="width:100px">',
		'		<option value="0">未审核</option>',
		'		<option value="1">已审核</option>',
		'	</select>',
		'</div>',
		'<button type="button" id="btn_user_pass" class="btn btn-success pull-left">审核</button>'
	].join('');

	//	var operate = {
	//		field: 'operate',
	//		title: '操作',
	//		events: {
	//			'click .fn_userInfo': fn_userInfo,
	//			'click .fn_attachment': fn_attachment
	//		},
	//		formatter: function() {
	//			return [
	//				'<a class="fn_userInfo tr_link" href="#" data-toggle="tooltip" title="用户信息"><i class="fa fa-address-card-o"></i></a>',
	//				'<a class="fn_attachment tr_link" href="#" data-toggle="tooltip" title="附件"><i class="fa fa-paperclip"></i></a>'
	//			].join('');
	//		}
	//	}

	$structure_usercheck.vw_structure('destroy').vw_structure({
		showSearchtree: false,
		edittable: {
			type: "table",
			showInsertData: false,
			showErrorlog: false,
			showNewData: false,
			showEdit: false,
			//			operate: operate,
			ExtraTools: html,
			onAllEvents: function() {
				$fn_UserPass.prop('disabled', !$structure_usercheck.vw_structure('getEdittable').vw_edittable('getSelections').length);
			}
		},
		interfaceAddress: VW_INTERFACE.WEBSERVICE.UserManage,
		tableDataURL: 'GetVerifyUser',
		extrapara: {
			checkstat: checkstat
		},
	});

	$structure_usercheck.vw_structure('getEdittable').vw_edittable('ajaxLoadTableData', 1, 1);

	$selectUserCheck = $('#select_userCheck');
	$fn_UserPass = $("#btn_user_pass");

	$fn_UserPass.click(fn_UserPass);
	$selectUserCheck.select2().on('select2:select', function(e) {
		InitTab_UserCheck(e.params.data.id);
	});
}

function fn_UserPass() {
	var dom = [
		'<div style="margin:10px;padding-left:10px;background-color: #f7f7f9;border: 1px solid #e1e1e8; border-radius: 4px;">',
		'	<strong>审核状态：</strong>',
		'	<label class="radio-inline">',
		'		<input type="radio" name="inlineRadioOptions" value="1"> 通过',
		'	</label>',
		'	<label class="radio-inline">',
		'		<input type="radio" name="inlineRadioOptions" value="0"> 不通过',
		'	</label>',
		'</div>',
		'<div style="margin:10px">',
		'	<textarea id="textarea_msg" style="width:100%;resize:none" rows="6" placeholder="请输入审核意见..."></textarea>',
		'</div>'
	].join('');

	bDialog.open({
		title: "审核意见",
		dom: dom,
		dialogMaxButton: false,
		customClass: 'blue',
		width: 400,
		height: 400,
		fnButton: true,
		fnButtonName: "审核",
		onShow: function(dialog) {
			$(dialog.dialog[0]).find('.radio-inline').css({
				"font-size": "18px",
				"padding": "10px 40px",
			});

			$(dialog.dialog[0]).find("input[name='inlineRadioOptions']").css({
				"margin-top": "6px",
				"margin-left": "-18px"
			});

			$($(dialog.dialog[0]).find('.radio-inline')[0]).css({
				"color": "green"
			});

			$($(dialog.dialog[0]).find('.radio-inline')[1]).css({
				"color": "red"
			});
		},
		fn: function() {
			var stat = $("input[name='inlineRadioOptions']:checked").val();
			var msg = $('#textarea_msg').val();

			if(stat == undefined) {
				bDialog.msgPopup("warning", "提示", "请选择审核结果!");
				return;
			}

			if(stat == 0 && msg == "") {
				bDialog.msgPopup("warning", "提示", "请输入审核意见!");
				return;
			}

			bDialog.close({
				result: {
					stat: $("input[name='inlineRadioOptions']:checked").val(),
					msg: $('#textarea_msg').text()
				}
			});
		},
		callback: function(data) {
			if(data.results != null) {
				var ids = $.map($table_usercheck.bootstrapTable('getSelections'), function(row) {
					return row[_idField];
				});

				vw_common.customAjax({
					url: VW_INTERFACE.WEBSERVICE.UserManage("UserVerify"),
					type: "GET",
					dataType: "json",
					data: {
						userID: _userID,
						id: ids.join(','),
						checkstage: _checkstage,
						status: data.results[0].result.stat,
						opinion: data.results[0].result.msg
					}
				}, function(e) {
					init(_checkstage, _canRollBack);
					$.Notify({
						caption: "成功",
						content: "审核结果已提交",
						type: "success"
					});
				});
			}
		},
	}, {
		messageType: 'confirm',
		cancel: function() {}
	});
}

function InitTab_Usermng() {
	$structure_usermng.vw_structure('destroy').vw_structure({
		searchtree: {
			menu: [{
				id: 1,
				text: "用户组"
			}],
			showEdit: true,
		},
		edittable: {
			showImportData: false,
			showNewData: true,
			showErrorlog: true,
			showEdit: true,
			showExport: true,
			ignoreVisible: true,
			ExtraTools: '<button type="button" id="fn_resetPassWord" class="btn btn-primary">重置密码</button>',
			onInitialized: function() {
				$('#fn_resetPassWord').click(fn_resetPassWord);
			},
			onAllEvents: function() {
				$('#fn_resetPassWord').prop('disabled', !$structure_usermng.vw_structure('getEdittable').vw_edittable('getSelections').length);
			}
		},
		interfaceAddress: VW_INTERFACE.WEBSERVICE.UserManage,
	});
}

function fn_resetPassWord() {
	if(!_uEmail) {
		$.Notify({
			caption: "错误",
			content: "该用户未设置邮箱，无法接收重置后的随机密码。",
			type: "alert"
		});
		return;
	}
	vw_common.customAjax({
		url: VW_INTERFACE.WEBSERVICE.LoginManage("ResetPwd"),
		type: "POST",
		dataType: "json",
		data: {
			"email": _uEmail
		}
	}, function() {
		$.Notify({
			caption: "成功",
			content: "密码已重置",
			type: "success"
		});
	});
}

function InitTab_UserAuthority() {
	var custom = [
		'<div class="row">',
		'	<div class="col-md-6" id="ttr">',
		'		<div class="row bg-info" style="margin: 0">',
		'			<div class="col-md-10">',
		'				<h4 class="text-center">功能权限设置</h4>',
		'			</div>',
		'			<div class="col-md-2">',
		'				<button type="button" id="saveAuthFn" class="btn btn-success pull-right" style="margin-top: 3px;"><i class="fa fa-save"></i>  保存</button>',
		'			</div>',
		'		</div>',
		'		<div id="fn_authoruty"></div>',
		'	</div>',
		'	<div class="col-md-6">',
		'		<div class="row bg-info" style="margin: 0">',
		'			<div class="col-md-10">',
		'				<h4 class="text-center">数据（表）权限设置</h4>',
		'			</div>',
		'			<div class="col-md-2">',
		'				<button type="button" id="saveAuthTable" class="btn btn-success pull-right" style="margin-top: 3px;"><i class="fa fa-save"></i>  保存</button>',
		'			</div>',
		'		</div>',
		'		<div id="data_authoruty"></div>',
		'	</div>',
		'</div>'
	].join('');

	$structure_authoruty.vw_structure('destroy').vw_structure({
		showEdittable: false,
		customTab: custom,
		searchtree: {
			menu: [{
				id: 1,
				text: "角色"
			}],
			showEdit: true,
			onTreeSelected: function(node) {
				if(node.isChild == false) {
					_nodeAuthority = node.id;

					$fn_authoruty.vw_searchtree('destroy').vw_searchtree({
						extrapara: {
							catalogID: _nodeAuthority,
						},
						showCheckbox: true,
						checkStatName: "isSelect",
						emptyIcon: '',
						height: $structure_authoruty.height() - 105,
						dataurl: VW_INTERFACE.WEBSERVICE.UserManage("GetFuncByRoleID")
					});

					$data_authoruty.vw_searchtree('destroy').vw_searchtree({
						extrapara: {
							catalogID: _nodeAuthority,
						},
						showCheckbox: true,
						checkStatName: "isSelect",
						emptyIcon: '',
						height: $structure_authoruty.height() - 105,
						dataurl: VW_INTERFACE.WEBSERVICE.UserManage("GetTableByRoleID")
					});
				}
			}
		},
		interfaceAddress: VW_INTERFACE.WEBSERVICE.UserManage,
		treeInfoURL: 'GetRoleInfo',
		treeDataURL: 'GetRole',
		treeDeleteURL: "DeleteRole",
		treeSaveURL: 'SaveRoleInfo',
		onInitialized: function() {
			$fn_authoruty = $('#fn_authoruty');
			$data_authoruty = $('#data_authoruty');
			$('#saveAuthFn').click(saveAuthFn);
			$('#saveAuthTable').click(saveAuthTable);
		}
	});
}

function saveAuthFn() {
	var ids = [];
	$.each($fn_authoruty.vw_searchtree('GetChecked'), function(k, val) {
		ids.push(val.id);
	});

	vw_common.customAjax({
		url: VW_INTERFACE.WEBSERVICE.UserManage("SaveFunction"),
		type: "GET",
		dataType: "json",
		data: {
			catalogID: _nodeAuthority,
			ids: ids.join(',')
		}
	}, function() {
		$.Notify({
			caption: "成功",
			content: "权限修改保存成功",
			type: "success"
		});
	});
}

function saveAuthTable() {
	var ids = [];
	$.each($data_authoruty.vw_searchtree('GetChecked'), function(k, val) {
		ids.push({
			id: val.id,
			pid: val.pid
		});
	});

	vw_common.customAjax({
		url: VW_INTERFACE.WEBSERVICE.UserManage("SaveTableFunction"),
		type: "POST",
		dataType: "json",
		data: {
			catalogID: _nodeAuthority,
			ids: JSON.stringify(ids)
		}
	}, function() {
		$.Notify({
			caption: "成功",
			content: "权限修改保存成功",
			type: "success"
		});
	});
}

function InitTab_UserData() {
	$structure_data.empty().append([
		'<div class="row">',
		'	<div class="col-md-9">',
		'		<div id="userData_table"></div>',
		'	</div>',
		'	<div class="col-md-3">',
		'		<div class="row bg-info" style="margin: 0">',
		'			<div class="col-md-10">',
		'				<h4 id="userData_tree_id" class="text-center"></h4>',
		'			</div>',
		'			<div class="col-md-2">',
		'				<button type="button" id="saveUserData" class="btn btn-success pull-right" style="margin-top: 3px;"><i class="fa fa-save"></i>  保存</button>',
		'			</div>',
		'		</div>',
		'		<div id="userData_tree"></div>',
		'	</div>',
		'</div>'
	].join(''));

	$structure_data.css({
		"background-color": "#FFFFFF",
		"padding": "10px",
		"border-radius": "4px"
	});

	$userData_table = $('#userData_table');
	$userData_tree = $('#userData_tree');

	$userData_table.vw_edittable('destroy').vw_edittable({
		type: "table",
		showNewData: false,
		showErrorlog: false,
		showEdit: false,
		ExtraTools: '<button type="button" id="fn_setValue" class="btn btn-primary">同步用户设置</button>',
		height: $(window).height() - 100,
		dataURL: VW_INTERFACE.WEBSERVICE.UserManage("LoadDataFunction"),
		onInitialized: function() {
			$('#fn_setValue').click(fn_setValue);
			$('#saveUserData').click(saveUserData);
		},
		onRowClicked: function(row, $element, field) {
			_userData_id = row[$userData_table.vw_edittable('getOptions').idField];
			$('#userData_tree_id').text(row['用户名']);
			$userData_tree.vw_searchtree('destroy').vw_searchtree({
				extrapara: {
					id: _userData_id,
				},
				showCheckbox: true,
				checkStatName: "isSelect",
				emptyIcon: '',
				height: $(window).height() - 170,
				dataurl: VW_INTERFACE.WEBSERVICE.UserManage("GetDataByUserID")
			});
		}
	}).vw_edittable('ajaxLoadTableData', -1);
}

function fn_setValue() {
	var ids = [];
	var idField = $structure_data.vw_structure('getEdittable').vw_edittable('getOptions').idField;
	$.each($structure_data.vw_structure('getEdittable').vw_edittable('getSelections'), function(k, val) {
		ids.push(val[idField]);
	});

	vw_common.customAjax({
		url: VW_INTERFACE.WEBSERVICE.UserManage("SetDataFunction"),
		type: "POST",
		dataType: "json",
		data: {
			ids: ids.join(',')
		}
	}, function() {
		InitTab_UserData();
		$.Notify({
			caption: "成功",
			content: "用户数据权限同步成功",
			type: "success"
		});
	});
}

function saveUserData() {
	var ids = [];
	$.each($userData_tree.vw_searchtree('GetChecked'), function(k, val) {
		ids.push({
			id: val.id,
			pid: val.pid,
			text: val.name
		});
	});

	vw_common.customAjax({
		url: VW_INTERFACE.WEBSERVICE.UserManage("SaveDataFunction"),
		type: "POST",
		dataType: "json",
		data: {
			id: _userData_id,
			ids: JSON.stringify(ids)
		}
	}, function() {
		$.Notify({
			caption: "成功",
			content: "用户数据权限保存成功",
			type: "success"
		});
	});
}